//
//  RotateCameraViewController.m
//  CumtomerCamerProject
//
//  Created by 蓓蕾 on 2021/11/23.
//

#import "RotateCameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"

API_AVAILABLE(ios(10.0))
@interface RotateCameraViewController ()<AVCapturePhotoCaptureDelegate>

@property (nonatomic, retain) AVCaptureSession *session;
@property (nonatomic, retain) AVCaptureDeviceInput *input;
@property (nonatomic, retain) AVCaptureDevice *device;
@property (nonatomic, retain) AVCapturePhotoOutput *imageOutput;
@property (nonatomic, retain) AVCaptureVideoPreviewLayer *preview;
@property (nonatomic, retain) AVCapturePhotoSettings *outputSettings;

@property (nonatomic, strong) UIImage *currentImage;

@end

@implementation RotateCameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    [self initCameraInPosition:YES];
}

- (void)deviceOrientationDidChange
{
    NSLog(@"NAV deviceOrientationDidChange:%ld",(long)[UIDevice currentDevice].orientation);
    if([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {//设备朝上
        NSLog(@"【设备朝上】123");
        [self orientationChange:NO withDeviceOrientation:UIDeviceOrientationPortrait];
    }else if([UIDevice currentDevice].orientation == UIDeviceOrientationPortraitUpsideDown){//设备朝下
        NSLog(@"【设备朝下】");
        [self orientationChange:NO withDeviceOrientation:UIDeviceOrientationPortraitUpsideDown];
    }else if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft) {//设备朝左【旋转反向】
        NSLog(@"【设备朝左】456");
        [self orientationChange:YES withDeviceOrientation:UIDeviceOrientationLandscapeLeft];
    }else if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight)
    {//设备朝右【旋转正常】
        NSLog(@"【设备朝右】789");
        [self orientationChange:YES withDeviceOrientation:UIDeviceOrientationLandscapeRight];
    }
}

- (void)orientationChange:(BOOL)landscapeRight withDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    
    
    switch (deviceOrientation) {
        case UIDeviceOrientationPortrait:
        {//设备朝上
//            [UIView animateWithDuration:0.02 animations:^{
                self.view.transform = CGAffineTransformMakeRotation(0);
                self.view.bounds = CGRectMake(0, 0, width, height);
//            }];
        }
            break;
        case UIDeviceOrientationPortraitUpsideDown:
        {//设备朝下
//            [UIView animateWithDuration:0.02 animations:^{
                self.view.transform = CGAffineTransformMakeRotation(M_PI_2 * 2);
                self.view.bounds = CGRectMake(0, 0, width, height);
//            }];
        }
            break;
        case UIDeviceOrientationLandscapeLeft:
        {//设备朝左
//            [UIView animateWithDuration:0.02 animations:^{
                self.view.transform = CGAffineTransformMakeRotation(-M_PI_2);
                self.view.bounds = CGRectMake(0, 0, height, width);
//            }];
        }
            break;
        case UIDeviceOrientationLandscapeRight:
        {//设备朝右
//            [UIView animateWithDuration:0.02 animations:^{
                self.view.transform = CGAffineTransformMakeRotation(M_PI_2);
                self.view.bounds = CGRectMake(0, 0, height, width);
//            }];
        }
            break;
            
        default:
            break;
    }
}

- (void)initCameraInPosition:(BOOL)isBack {
    self.session = [AVCaptureSession new];
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    NSArray *devices = [NSArray new];
//    devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    if (@available(iOS 10.0, *)) {
        AVCaptureDeviceDiscoverySession *captureDeviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera]
                                                                                                                                mediaType:AVMediaTypeVideo
                                                                                                                                 position: AVCaptureDevicePositionUnspecified];
        devices = [captureDeviceDiscoverySession devices];
    } else {
        devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    }
    
    for (AVCaptureDevice *device in devices) {
        if (isBack) {
            if ([device position] == AVCaptureDevicePositionBack) {
                _device = device;
                break;
            }
        }else {
            if ([device position] == AVCaptureDevicePositionFront) {
                _device = device;
                break;
            }
        }
    }
    
    NSError *error;
    
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if (@available(iOS 11.0, *)) {
        self.imageOutput = [[AVCapturePhotoOutput alloc] init];
        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
        _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    } else if (@available(iOS 10.0, *)) {
        self.imageOutput = [[AVCapturePhotoOutput alloc] init];
        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecJPEG};
        _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    } else {
        
    }
    
    
    [self.imageOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
    [self.session addOutput:self.imageOutput];
    self.preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [self.preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [self.preview setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view.layer addSublayer:self.preview];
    [self.session startRunning];
    
    UIButton *takeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    takeButton.frame = CGRectMake((self.view.frame.size.width - 70)/2, self.view.frame.size.height - 100, 70, 70);
    takeButton.layer.masksToBounds = YES;
    takeButton.layer.cornerRadius = takeButton.frame.size.height/2;
    takeButton.backgroundColor = [UIColor colorWithWhite:1 alpha:0.7];
    [takeButton setTitle:@"拍照" forState:UIControlStateNormal];
    takeButton.titleLabel.font = [UIFont systemFontOfSize:16];
    takeButton.titleLabel.numberOfLines = 0;
    [takeButton setTitleColor:[UIColor colorWithRed:40.2f/255 green:180.2f/255 blue:247.2f/255 alpha:0.9] forState:UIControlStateNormal];
    [takeButton addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:takeButton];
    
}

- (void)takePhoto {
    if (@available(iOS 11.0, *)) {
        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
        AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
        [self.imageOutput capturePhotoWithSettings:outputSettings delegate:self];
    } else if (@available(iOS 10.0, *)){
        NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecJPEG};
        AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
        [self.imageOutput capturePhotoWithSettings:outputSettings delegate:self];
    }
    else
    {
        
    }
}

//captureOutput:didFinishProcessingPhoto:error:

-(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error
API_AVAILABLE(ios(11.0)){
    if (error != nil){
            NSLog(@"%s: %@", "Error in capture process", error.debugDescription);
        }
    
    NSData *currentImageData = nil;
        NSData *imageData = [photo fileDataRepresentation];
        
        if (imageData == nil){
            NSLog(@"%s", "unable to create image data");
        }
        currentImageData = imageData;
//        NSData *photoData = UIImageJPEGRepresentation([[UIImage alloc] initWithData:imageData], 0.0);
        
        
    
    UIImage *image = [UIImage imageWithData:currentImageData];
    _currentImage = image;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

#pragma mark AVCapturePhotoCaptureDelegate
- (void)captureOutput:(AVCapturePhotoOutput *)captureOutput didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error  API_AVAILABLE(ios(10.0)){
    
    NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
    UIImage *image = [UIImage imageWithData:data];
    _currentImage = image;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
//        _takePhotoSuccess();
    }
    NSLog(@"+++++++++++%@", msg);
    [self showImage];
}

-(void)showImage
{
    
//    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    
    
    if([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {//设备朝上
        NSLog(@"【设备朝上】123");
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        [self.view addSubview:imageView];
        imageView.image = _currentImage;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImageView:)];
        [imageView addGestureRecognizer:tapGesture];
    }else if([UIDevice currentDevice].orientation == UIDeviceOrientationPortraitUpsideDown){//设备朝下
        NSLog(@"【设备朝下】");
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        [self.view addSubview:imageView];
        imageView.image = _currentImage;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImageView:)];
        [imageView addGestureRecognizer:tapGesture];
    }else if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft) {//设备朝左【旋转反向】
        NSLog(@"【设备朝左】456");
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width)];
        [self.view addSubview:imageView];
        imageView.image = _currentImage;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImageView:)];
        [imageView addGestureRecognizer:tapGesture];
    }else if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight)
    {//设备朝右【旋转正常】
        NSLog(@"【设备朝右】789");
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width)];
        [self.view addSubview:imageView];
        imageView.image = _currentImage;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImageView:)];
        [imageView addGestureRecognizer:tapGesture];
    }
    
    
    
    
}

-(void)removeImageView:(UITapGestureRecognizer *)gesture
{
    UIView *gestureView = gesture.view;
    [gestureView removeFromSuperview];
}

- (void)startRunning{
    [_session startRunning];
}

- (void)stopRunning{
    [_session stopRunning];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AppDelegate *appdelegate = ((AppDelegate *)[[UIApplication sharedApplication] delegate]);
    appdelegate.allowRotation = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    AppDelegate *appdelegate = ((AppDelegate *)[[UIApplication sharedApplication] delegate]);
    appdelegate.allowRotation = NO;
}

-(void)dealloc
{
    NSLog(@"销毁视图控制器");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
